package org.auf.controllers;

import java.io.IOException;
import java.util.Collection;
import java.util.Date;

import org.auf.core.Controller;
import org.auf.model.dao.IEventDAO;
import org.auf.model.dao.IPointedDAO;
import org.auf.model.jdbc.EventDAOJDBC;
import org.auf.model.jdbc.PointedDAOJDBC;

import org.auf.to.Event;
import org.auf.to.User;
import org.apache.log4j.Logger;


public class JoinEventController extends Controller{

	static Logger log = Logger.getLogger(JoinEventController.class.getName());
	@Override
	public void show() {
		String id;
		id = (String) request.getParameter("id");
		IEventDAO eventDAO = EventDAOJDBC.getInstance();
		Event actual = eventDAO.selectEvent(id);
	
		if(actual==null)
			log.error("El evento es nulo");
		
		IPointedDAO pointedDAO =  new PointedDAOJDBC();
		
		Collection<User> geek = pointedDAO.selectGeeksByEvent(actual);
		Collection<User> volunteer = pointedDAO.selectVolunteersByEvent(actual);
		
		if(geek==null)
			log.error("La lista de frikis es nula");
		if(volunteer==null)
			log.error("La lista de voluntarios es nulo");
		
		if(new Date().before(actual.getDateLimit())){
			
			if(user.getGeek()){
				
				
				if(geek.size()<actual.getGeeksSlots()){
					
					pointedDAO.insertPointed(actual, user);
				}		
			}
			
			if(!user.getGeek()){
				if(volunteer.size()<actual.getVolunteersSlots()){
				
					pointedDAO.insertPointed(actual, user);			
				}
		}
				
		try {
		response.sendRedirect(BaseURLs.SHOW_MESSAGE_EVENT+"&id="+actual.getId());
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
  }	
 }
}